var niic = require("@native.iic");
var sys = require("@native.builtin");


SLAVE = 0;
MASTER = 1;

function IIC(id) {
    this.id = id;

    this.write = function(reg, buffer){
        if(typeof(reg) != "number")
            return undefined;
        if(buffer == undefined || buffer.length == 0)
            return undefined;
        var size = buffer.length;
        if(size <= 0)
            return undefined;
        var data = sys.malloc(size);
        if(data == null)
            return undefined;
        sys.copy(data, buffer, size);
        niic.write(this.id, reg, data, size);
        sys.free(data);
    };

    this.read = function (reg, num) {
        if (typeof reg != "number") return undefined;
        if (typeof num != "number" || num == 0) return undefined;
        var buffer = sys.malloc(num);
        if (buffer == null) return undefined;
        var ret = niic.read(this.id, reg, buffer, num);
        if (ret == 0) {
            sys.free(buffer);
            return sys.toJsArray(buffer, num);
        }
        sys.free(buffer);
        return undefined;
    };

    this.close = function () {
        niic.close(this.id);
    };
}

function open(opt){
    if(opt == undefined)
        return undefined;
    var id = opt["id"];
    var mode = opt["mode"];
    var addr = opt["addr"];
    var freq = opt["freq"];

    if (
        id == undefined ||
        mode == undefined ||
        addr == undefined ||
        freq == undefined
    )
        return undefined;

    if (
        typeof id != "number" ||
        typeof mode != "number" ||
        typeof addr != "number" ||
        typeof freq != "number"
    )
        return undefined;

    if(niic.open(id, mode, addr, freq) == 0)
        return new IIC(id);
    return undefined;
}

